/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-12-02 11:50:21
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2022-12-02 11:59:02
 */
import CryptoJS from 'crypto-js'

// 如果是接口加密需要和后端一致
const KEY = CryptoJS.enc.Utf8.parse('1987781191288888');
const IV = CryptoJS.enc.Utf8.parse('1987781191288888');

export default {

    /**
     * 加密
     * @param {*} word
     * @param {*} keyStr
     * @param {*} ivStr
     */
    encrypt(word, keyStr, ivStr) {
        let key = KEY;
        let iv = IV;
        if (keyStr) {
            key = CryptoJS.enc.Utf8.parse(keyStr);
            iv = CryptoJS.enc.Utf8.parse(ivStr);
        }
        let srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7 //   Pkcs7   ZeroPadding
        });
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    },

    /**
     * 解密
     * @param {*} word
     * @param {*} keyStr
     * @param {*} ivStr
     */
    decrypt(word, keyStr, ivStr) {
        let key = KEY;
        let iv = IV;

        if (keyStr) {
            key = CryptoJS.enc.Utf8.parse(keyStr);
            iv = CryptoJS.enc.Utf8.parse(ivStr);
        }

        let base64 = CryptoJS.enc.Base64.parse(word);
        let src = CryptoJS.enc.Base64.stringify(base64);

        let decrypt = CryptoJS.AES.decrypt(src, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.ZeroPadding
        });

        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    },

    // 视洞摄像头加密
    encryption(params) {
        let { data, type, param, key } = params;
        // console.log(params)
        const result = JSON.parse(JSON.stringify(data));
        if (type === 'Base64') {
            param.forEach((ele) => {
                result[ele] = btoa(result[ele]);
            });
        } else {
            param.forEach((ele) => {
                let data = result[ele];
                key = CryptoJS.enc.Latin1.parse(key);
                let iv = key;
                // 加密
                let encrypted = CryptoJS.AES.encrypt(data, key, {
                    iv: iv,
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.ZeroPadding
                });
                result[ele] = encrypted.toString();
            });
        }
        return result;
    }
}